<template>
    <div
        class="login-container flex-center-box relative min-w-page h-screen w-full"
        :style="{ background: `url(${useImage('login', 'background.png')})` }"
    >
        <img class="logo top-10 left-14 absolute" src="@assets/images/common/logo.png"/>
        <div class="login-content rounded-20 flex bg-white bg-opacity-30 overflow-hidden">
            <!-- 左侧轮播图 -->
            <el-carousel arrow="never" class="w-1/2 h-full" height="610px">
                <el-carousel-item v-for="item in 5" :key="item">
                    <img class="w-full" :src="useImage('login', `swiper${item}.png`)"/>
                </el-carousel-item>
            </el-carousel>
            <!-- 右侧表单 -->
            <div class="form-box w-1/2 box-border" v-loading="isSubmit">
                <span class="welcome z-10 text-42 tracking-5 relative">欢迎登录</span>
                <el-form
                    ref="ruleFormRef"
                    :model="ruleForm"
                    :rules="rules"
                    class="ruleForm"
                    size="large"
                    status-icon
                >
                    <!-- 账号 -->
                    <div class="flex-items-box w-full mb-60">
                        <Icon :class="['mr-10', { 'text-primary': focusNum === 1 }]" :size="25" name="User"/>
                        <el-form-item prop="username">
                            <el-input
                                type="text"
                                placeholder="请输入用户名"
                                clearable
                                v-model="ruleForm.username"
                                @focus="focusNum = 1"
                            />
                        </el-form-item>
                    </div>
                    <!-- 密码 -->
                    <div class="flex-items-box w-full mb-60">
                        <Icon :class="['mr-10', { 'text-primary': focusNum === 2 }]" :size="25" name="Unlock"/>
                        <el-form-item prop="password">
                            <el-input
                                type="password"
                                placeholder="请输入密码"
                                v-model="ruleForm.password"
                                clearable
                                show-password
                                @focus="focusNum = 2"
                                @keyup.enter.native="login(ruleFormRef)"
                            />
                        </el-form-item>
                    </div>
                </el-form>
                <el-button type="warning" @click="login(ruleFormRef)">
                    登录
                </el-button>
            </div>
        </div>
        <p class="absolute bottom-16 text-t-secondary text-12 left-1/2 -translate-x-1/2">
            <a href="https://beian.miit.gov.cn" target="_blank">蜀ICP备2023008463号-1</a> Designed By Gan Wen Jing.
        </p>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { FormInstance, FormRules } from 'element-plus'
import { httpLoginSystem, LoginParams } from '@api/module/system'
import { ElMessages, Storage, timeout, useImage } from '@utils/methods'
import Icon from '@components/Icon/index.vue'
import './index.less'

const router = useRouter()

// 当前聚焦表单
const focusNum = ref(0)
// 表单实例
const ruleFormRef = ref<FormInstance>()
// 表单提交状态
const isSubmit = ref(false)

// 验证用户名
const validateUsername = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入用户名'))
    } else if (!/^[a-zA-Z]{4,10}$/.test(value)) {
        callback(new Error('请输入由字母组成的 4-10 位用户名!'))
    } else {
        callback()
    }
}
// 验证密码
const validatePassword = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入密码'))
    } else if (!/^[a-zA-Z][a-zA-Z0-9]{7,13}$/.test(value)) {
        callback(new Error('请输入由字母开头，数字和字母组成的 8-14 位密码!'))
    } else {
        callback()
    }
}
// 校验规则
const rules = reactive<FormRules>({
    username: [{ validator: validateUsername, trigger: 'blur' }],
    password: [{ validator: validatePassword, trigger: 'blur' }]
})

// 表单信息
const ruleForm = reactive<LoginParams>({
    username: '',
    password: ''
})

/**
 * 点击登录
 * */
const login = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(valid => {
        if (valid) {
            isSubmit.value = true
            // 登录请求
            httpLoginSystem(ruleForm).then(({ success, message, data }) => {
                if (success) {
                    const { token, userInfo } = data
                    Storage.set('token', token)
                    Storage.set('systemInfo', userInfo)
                    router.push('/').then(async () => {
                        await timeout(200)
                        ElMessages.success('登录成功')
                    })
                } else {
                    ElMessages.error(message!)
                }
            }).finally(() => {
                isSubmit.value = false
            })
        }
    })
}
</script>
